import 'dart:io';

import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:permission_handler/permission_handler.dart';

import '../widgets/dialog.dart';

bool isAudio(String name, String type) {
  if (name == "bgm" || name == "bg" || name == "sound") {
    return false;
  }
  if (type == "audio" && name != "bgm" && name != "sound") {
    return true;
  } else {
    return false;
  }
}

bool isVideo(String name, String type) {
  if (name == "bgm" || name == "bg" || name == "sound" || name == "animation") {
    return false;
  }
  if (type == "video" && name != "bg") {
    return true;
  } else {
    return false;
  }
}

bool isText(String name, String type) {
  if (name == "bgm" || name == "bg" || name == "sound" || name == "animation" || name == "role" || name == "btn" || name == "btnAd" || name == "level") {
    return false;
  }
  if (type == "str" || (isEmpty(type) && name == "str") || (isEmpty(type) && isEmpty(name))) {
    return true;
  } else {
    return false;
  }
}

bool isImg(String name, String type) {
  if (name == "bgm" || name == "bg" || name == "sound" || name == "animation" || name == "role" || name == "level") {
    return false;
  }
  if (type == "img" && name != "bg") {
    return true;
  } else {
    return false;
  }
}

bool isBtn(String name) {
  if (name == "btn" || name == "btnAd") {
    return true;
  }
  return false;
}

bool isBtnAd(String name) {
  if (name == "btnAd") {
    return true;
  }
  return false;
}

bool isBtnInput(String name) {
  if (name == "isBtnInput") {
    return true;
  }
  return false;
}

bool isBgm(String name) {
  if (name == "bgm") {
    return true;
  }
  return false;
}

bool isBg(String name) {
  if (name == "bg") {
    return true;
  }
  return false;
}

bool isSound(String name, String type) {
  if ((type == "bg" || type == "audio") && name == "sound") {
    return true;
  }
  return false;
}

bool isEmpty(String? string) {
  if (string != null && string.isNotEmpty && string != "null" && string != "nil" && string != "none") {
    return false;
  } else {
    return true;
  }
}

bool isMarkdown(String text) {
  final markdownPattern = RegExp(
    r'(^#{1,6}\s+.*$|' // 标题
    r'(\*\*|__)(.*?)\1|' // 加粗
    r'(\*|_)(.*?)\1|' // 斜体
    r'$begin:math:display$.*?$end:math:display$$begin:math:text$.*?$end:math:text$|' // 链接
    r'^>.*$|' // 引用
    r'```.*?```|`.*?`)', // 代码块
    multiLine: true,
  );
  return markdownPattern.hasMatch(text);
}

double toDouble(dynamic value) {
  if (value is num) {
    return value.toDouble();
  } else if (value is String) {
    return double.tryParse(value) ?? 0.0;
  }
  return 0.0;
}

int toInt(dynamic value) {
  if (value is num) {
    return value.toInt();
  } else if (value is String) {
    return int.tryParse(value) ?? 0;
  }
  return 0;
}

String toString(dynamic value) {
  if (value is String) {
    return value;
  } else if (value is num) {
    return value.toString();
  } else if (value == null) {
    return '';
  } else {
    return value.toString();
  }
}

String timeAgoSinceDate(String dateString) {
  DateTime date = DateTime.parse(dateString);
  DateTime now = DateTime.now();

  // 计算时间差
  Duration diff = now.difference(date);

  // 根据差值返回相应的描述
  if (diff.inSeconds < 60) {
    return "刚刚";
  } else if (diff.inMinutes < 60) {
    return "${diff.inMinutes}分钟前";
  } else if (diff.inHours < 24) {
    return "${diff.inHours}小时前";
  } else if (diff.inDays < 30) {
    return "${diff.inDays}天前";
  } else if (diff.inDays < 365) {
    return "${(diff.inDays / 30).floor()}个月前";
  } else {
    return "超过1年前";
  }
}

bool isImageFile(String fileExtension) {
  List<String> imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'tif', 'tiff', 'ico', 'webp'];
  return imageExtensions.contains(fileExtension);
}

String convertImageUrl(String? imageUrl) {
  if (imageUrl == null) return "";
  final regex = RegExp(r'^(https?://)img\.(.*)$');
  return imageUrl.replaceAllMapped(regex, (match) {
    return "${match[1]}ali-img.${match[2]}";
  });
}

String formatSeconds(int totalSeconds) {
  int minutes = totalSeconds ~/ 60;
  int seconds = totalSeconds % 60;

  return '${minutes.toString().padLeft(2, '0')}:${seconds.toString().padLeft(2, '0')}';
}

String formatSeconds2(int totalSeconds) {
  final duration = Duration(seconds: totalSeconds);
  final minutes = duration.inMinutes.remainder(60).toString().padLeft(2, '0');
  final seconds = (duration.inSeconds.remainder(60)).toString().padLeft(2, '0');
  return "$minutes'$seconds''";
}

String formatDate(int ts, {String pattern = 'yyyy/MM/dd'}) {
  DateTime date = DateTime.fromMillisecondsSinceEpoch(ts);
  return DateFormat(pattern).format(date);
}

class PermissionUtil {
  /// 安卓权限
  static List<Permission> androidPermissions = <Permission>[
    // 在这里添加需要的权限
    Permission.storage
  ];

  /// ios权限
  static List<Permission> iosPermissions = <Permission>[
    // 在这里添加需要的权限
    Permission.storage
  ];

  static Future<Map<Permission, PermissionStatus>> requestAll() async {
    if (Platform.isIOS) {
      return await iosPermissions.request();
    }
    return await androidPermissions.request();
  }

  static Future<Map<Permission, PermissionStatus>> request(Permission permission) async {
    final List<Permission> permissions = <Permission>[permission];
    return await permissions.request();
  }

  static bool isDenied(Map<Permission, PermissionStatus> result) {
    var isDenied = false;
    result.forEach((key, value) {
      if (value == PermissionStatus.denied) {
        isDenied = true;
        return;
      }
    });
    return isDenied;
  }

  static void showDeniedDialog(BuildContext context) {
    HDialog.show(
      context: context,
      title: '权限申请异常',
      content: '请在【应用信息】-【权限管理】中，开启全部所需权限，以正常使用功能',
      options: <DialogAction>[DialogAction(text: '去设置', onPressed: () => openAppSettings())],
    );
  }

  /// 检查权限
  static Future<bool> checkGranted(Permission permission) async {
    PermissionStatus storageStatus = await permission.status;
    if (storageStatus == PermissionStatus.granted) {
      return true;
    } else {
      return false;
    }
  }
}